﻿using NChardet;
using System;
using System.IO;
using System.Windows.Forms;

namespace RemoveCommentTool
{
    /// <summary>
    /// Description of MyCharsetDetectionObserver.
    /// </summary>
    public class MyCharsetDetectionObserver : NChardet.ICharsetDetectionObserver
    {
        public string Charset = null;

        public void Notify(string charset)
        {
            Charset = charset;
        }
    }
    class CharDet
    {
        public string DetectCurrentFileEncode(string filePath)
        {
            string outputString = "UTF-8";
            try
            {
                using (var br = new BinaryReader(new FileStream(filePath, FileMode.Open)))
                {
                    //bool found = false;
                    Detector det = new Detector();
                    MyCharsetDetectionObserver cdo = new MyCharsetDetectionObserver();
                    det.Init(cdo);
                    byte[] buf = br.ReadBytes((int)br.BaseStream.Length);
                    // Check if the stream is only ascii.
                    if (false == det.isAscii(buf, (int)br.BaseStream.Length))
                    {
                        // DoIt if non-ascii and not done yet.
                        det.DoIt(buf, (int)br.BaseStream.Length, false);
                    }
                    det.DataEnd();
                    if (cdo.Charset != null)
                    {
                        outputString = cdo.Charset;
                        //found = true;
                    }
                    //if (!found)
                    //{
                    //    string[] prob = det.getProbableCharsets();
                    //    for (int i = 0; i < prob.Length; i++)
                    //    {
                    //        //Console.WriteLine("Probable Charset = " + prob[i]);
                    //    }
                    //}
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Throw a exception:" + ex.ToString());
                throw ex;
            }
            return outputString;
        }
    }
}
